#! /usr/bin/env bash

POSITIONAL_ARGS=()

SIZE="1M"
RESIZE=""

while [[ $# -gt 0 ]]; do
  case $1 in
    -s|--size)
      SIZE="$2"
      shift # arg
      shift # val
      ;;
    -r|--resize)
      RESIZE="$2"
      shift # arg
      shift # val
      ;;    
    -*)
      echo "Unknown option $1"
      exit 1
      ;;
    *)
      POSITIONAL_ARGS+=("$1")
      shift
      ;;
  esac
done

NAME="${POSITIONAL_ARGS[0]}"

if [ "$NAME" == "" ]; then
    echo "name empty"
    exit 1
fi

if [ ! -x "$NAME" ]; then
    echo "does not exist"
    exit 1
fi

echo "processing ${NAME@Q} with imagemagick"

JPEG=$(echo "$NAME" | sed 's/ /_/g' | sed 's/[.]tiff$/.jpg/')

DO_RESIZE=""
if [ ! "$RESIZE" == "" ]; then
    DO_RESIZE="-resize $RESIZE"
fi

CMD="magick -verbose -define jpeg:extent=$SIZE ${NAME@Q} $DO_RESIZE ${JPEG@Q}"

echo "$CMD"
eval "$CMD"

